﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.Administration;

namespace Winwise.SPWebConfig.Core
{
    public class WebConfigJobDefinition : SPJobDefinition
    {
        private const string JobName = "winwise-job-webconfig-modification";

        [Persisted]
        private Guid _WebModifID;

        public Guid WebModifID
        {
            get { return _WebModifID; }
            set { _WebModifID = value; }
        }

        [Persisted]
        private WebModificationsUpgradeType _UpgradeType;

        public WebModificationsUpgradeType UpgradeType
        {
            get { return _UpgradeType; }
            set { _UpgradeType = value; }
        }



        public WebConfigJobDefinition()
        {

        }

        public WebConfigJobDefinition(SPService service)
            : base(JobName, service, null, SPJobLockType.None)
        {

        }

        public WebConfigJobDefinition(SPWebApplication webApp)
            : base(JobName, webApp, null, SPJobLockType.None)
        {

        }

        public override void Execute(Guid targetInstanceId)
        {
            if (Service != null && WebApplication == null)
            {
                SPWebService service = (SPWebService)base.Service;
                foreach (SPWebApplication application in service.WebApplications)
                {
                    ApplyModif(application);
                }
            }
            else
            {
                ApplyModif(WebApplication);
            }

        }

        private void ApplyModif(SPWebApplication webapp)
        {
            try
            {
                webapp.ApplyCustomWebConfigModificationsLocalServer(this.UpgradeType, WebModifID); ;

            }
            catch (Exception exception)
            {
                LoggingService.LogError("Job", exception.ToString());
            }
        }

    }
}
